package cn.ibizlab.util.tenant;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 为job等FeignClient添加默认的TenantId
 */
@Configuration
@ConditionalOnExpression("'${ibiz.tenant.enabled:false}'.equals('true')")
public class TenantFeignInterceptor implements RequestInterceptor {

    @Autowired
    private TenantProperties tenantProperties;

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if ((requestAttributes == null) && !ObjectUtils.isEmpty(tenantProperties.getTenantId())) {
            requestTemplate.header(this.tenantProperties.getTenantHeader(), new String[]{tenantProperties.getTenantId()});
            this.logger.info("tenant feign interceptor header:{}", requestTemplate);
        }
    }
}
